<?php


namespace App\HttpController\Api\System;


use App\Common\Redis;
use App\HttpController\Api\Base;
use App\Models\AuthModel;
use App\Models\AuthNodeModel;
use EasySwoole\ORM\DbManager;
use EasySwoole\Pool\Manager;
use EasySwoole\Validate\Validate;

class Auth extends Base
{
    public function list()
    {
        $this->in();

//        $res = AuthModel::getInstance()->list($this->page, $this->limit, $this->search);
//        $this->writeJson($res);
    }

    /**
     * @return bool
     * @throws \EasySwoole\ORM\Exception\Exception
     * @throws \Throwable
     * 删除用户
     */
    public function del()
    {
        $res = AuthModel::create()->where(['id' => $this->requestData['id']])->destroy();
        if ($res) {
            $this->writeJson($this->success('删除成功'));
        } else {
            $this->writeJson($this->error('删除失败'));
        }
        return false;
    }

    /**
     * @return bool
     * @throws \EasySwoole\ORM\Exception\Exception
     * @throws \Throwable
     * 用户状态
     */
    public function status()
    {
        $userData = $this->request()->getParsedBody();
        $res = AuthModel::create()->where(['id' => $userData['id']])->update(['status' => $userData['status']]);
        $msg = $userData['status'] ? '启用' : '禁用';
        if ($res) {
            $this->writeJson($this->success($msg . '成功'));
        } else {
            $this->writeJson($this->error($msg . '失败'));
        }
        return false;
    }

    public function add()
    {
        try {
            $userModel = AuthModel::create([
                'title' => trim($this->requestData['title']),
                'remark' => $this->requestData['remark'] ?? '',
            ]);
            $userModel->save();
            $this->writeJson($this->success('添加角色成功'));
        } catch (\Throwable $t) {
            $this->writeJson($this->error('添加角色异常'));
            $this->errorLog($t);
        }
        return false;
    }

    /**
     * @return bool
     * 编辑
     */
    public function edit()
    {
        try {
            AuthModel::getInstance()->update([
                'title' => trim($this->requestData['title']),
                'remark' => $this->requestData['remark'] ?? '',
            ], ['id' => $this->requestData['id']]);
            $this->writeJson($this->success('编辑角色成功'));
        } catch (\Throwable $t) {
            $this->writeJson($this->error('编辑角色异常'));
            $this->errorLog($t);
        }
        return false;
    }

    /**
     * @return bool
     * @throws \EasySwoole\ORM\Exception\Exception
     * @throws \Throwable
     * 授权
     */
    public function apply()
    {
        $nodeList = json_decode($this->requestData['node_id'], true);
        if (!is_array($nodeList)) {
            $this->error('node_id 节点id列表组格式不正确');
            return false;
        }
        DbManager::getInstance()->startTransaction();
        try {
            $authModel = AuthNodeModel::create();
            $authModel->destroy(['auth' => $this->requestData['id']]);
            $add = [];
            foreach ($nodeList as $v) {
                array_push($add, ['auth' => $this->requestData['id'], 'node' => $v]);
            }
            // 批量添加
            $authModel->saveAll($add);
            DbManager::getInstance()->commit();
            $this->writeJson($this->success('授权成功'));
        } catch (\Throwable $t) {
            DbManager::getInstance()->rollback();
            $this->writeJson($this->error('授权异常'));
            $this->errorLog($t);
        }
    }


    public function in()
    {
        $redis = Redis::getInstance();
        $res = $redis->pop('test');
        var_dump($redis->remove('test',$res));
    }

    protected function getValidateRule(?string $action): ?Validate
    {
        $validate = new Validate();
        switch ($action) {
            case 'status':
                $validate->addColumn('status', '角色状态')->required()->min(0)->max(1);
                break;
            case 'apply':
                $validate->addColumn('node_id', 'node_id 授权节点列表')->required();
                break;
        }

        $actionAll = ['del', 'status', 'apply', 'edit', 'info'];
        if (in_array($action, $actionAll)) {
            $validate->addColumn('id', '角色id')->required()->min(0);
        }
        if ($action == 'add' || $action == 'edit') {
            $validate->addColumn('title', '角色权限名称')->required();
            $validate->addColumn('remark', '备注')->lengthMax(100);
        }
        return $validate;
    }
}
